<template>
  <div class="customer-thing">
    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 客户信息展示区域 -->
      <section class="customer-info-section">
        <h2>客户信息概览</h2>
        <div class="info-card">
          <p><strong>姓名：</strong>{{ customerInfo.name }}</p>
          <p><strong>用户名：</strong>{{ username }}</p> <!-- 直接显示从本地存储获取的用户名 -->
        </div>
        <div class="info-card">
          <p><strong>最近登录时间：</strong>{{ currentLastLoginTime }}</p>
          <p><strong>联系电话：</strong>{{ customerInfo.telephone }}</p>
          <p><strong>地址：</strong>{{ customerInfo.address }}</p>
        </div>
      </section>

      <!-- AI 客服功能区域 -->
      <section class="ai-service-section">
        <div class="ai-chat-header">
          <h2>AI 客服</h2>
        </div>

        <div class="ai-chat-box">
          <div class="chat-header">
            <span>智能客服小助手</span>
          </div>
          <div class="chat-messages" id="chatMessages">
            <div
                v-for="(message, index) in chatMessages"
                :key="index"
                :class="['message', message.type]"
            >
              <p>{{ message.content }}</p>
            </div>
          </div>
          <div class="chat-input-area">
            <input
                v-model="chatInput"
                class="chat-input"
                placeholder="输入您的问题..."
                @keyup.enter="sendMessage"
            />
            <button class="send-btn" @click="sendMessage">发送</button>
          </div>
        </div>
      </section>

      <!-- 退出登录按钮 -->
      <div class="logout-container">
        <button class="logout-btn" @click="logout">退出登录</button>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  setup() {
    const chatInput = ref("");
    const chatMessages = ref([]);
    const username = ref(""); // 用户名称
    const customerInfo = ref({
      name: "",
      telephone: "",
      address: ""
    });
    const currentLastLoginTime = ref("");

    // 获取客户信息
    const fetchCustomerInfo = async () => {
      try {
        // 获取当前登录的用户名
        const currentUser = localStorage.getItem("username");
        if (!currentUser) {
          ElMessage.error("未找到当前登录用户，请重新登录！");
          return;
        }
        username.value = currentUser;

        // 调用后端接口查询用户数据
        const response = await axios.get(
            `http://localhost:8088/api/auth/customer/${currentUser}`
        );
        console.log(response.data);

        // 将后端返回的数据映射到前端的 customerInfo 对象
        customerInfo.value.name = response.data.customerName;
        customerInfo.value.telephone = response.data.telephone;
        customerInfo.value.address = response.data.address;

        console.log(customerInfo.value);
      } catch (error) {
        console.error("Error fetching customer info:", error);
        ElMessage.error("获取客户信息失败，请稍后再试！");
      }
    };

    // 设置当前登录时间
    const setLastLoginTime = () => {
      currentLastLoginTime.value = new Date().toLocaleString();
    };

    // 发送消息到后端
    const sendMessage = () => {
      if (!chatInput.value.trim()) return;

      // 添加用户消息到聊天记录
      chatMessages.value.push({
        type: "user-message",
        content: chatInput.value,
      });

      // 发送请求到后端
      axios
          .post("http://localhost:8088/api/chat/send", {
            sender: username.value,
            content: chatInput.value,
          })
          .then((response) => {
            // 添加AI消息到聊天记录
            chatMessages.value.push({
              type: "ai-message",
              content:
                  response.data.content || "感谢您的咨询，我们将尽快为您处理！",
            });
            scrollChatToBottom();
          })
          .catch((error) => {
            console.error("Error sending message:", error);
            chatMessages.value.push({
              type: "ai-message",
              content: "发送失败，请稍后再试。",
            });
          });

      // 清空输入框
      chatInput.value = "";
    };

    // 滚动聊天框到底部
    const scrollChatToBottom = () => {
      const chatMessagesElement = document.getElementById("chatMessages");
      if (chatMessagesElement) {
        chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
      }
    };

    // 退出登录
    const logout = () => {
      localStorage.removeItem("token");
      localStorage.removeItem("username"); // 同时移除用户名
      window.location.href = "/customer-login";
    };

    onMounted(() => {
      fetchCustomerInfo();
      setLastLoginTime();
    });

    return {
      chatInput,
      chatMessages,
      sendMessage,
      customerInfo,
      currentLastLoginTime,
      username, // 将 username 返回到模板中
      logout // 返回 logout 方法
    };
  },
};
</script>

<style scoped>
.customer-thing {
  display: flex;
  height: calc(100vh - 60px);
  background-color: #f9f9f9;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.customer-info-section {
  margin-bottom: 30px;
}
.customer-info-section h2 {
  font-size: 20px;
  margin-bottom: 15px;
}
.info-card {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

/* AI 客服区域样式 */
.ai-service-section {
  margin-top: 20px;
}
.ai-chat-header {
  margin-bottom: 15px;
}
.ai-chat-header h2 {
  font-size: 20px;
  margin-bottom: 15px;
}

.ai-chat-box {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chat-header {
  font-weight: bold;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chat-messages {
  height: 300px;
  overflow-y: auto;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 8px;
  max-width: 80%;
  word-break: break-word;
}

.user-message {
  background-color: #0095ff;
  color: white;
  margin-left: auto;
}

.ai-message {
  background-color: #f1f1f1;
  color: #333;
}

.chat-input-area {
  display: flex;
}

.chat-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  outline: none;
}

.send-btn {
  padding: 10px 20px;
  background-color: #0095ff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-btn:hover {
  background-color: #0077cc;
}

/* 退出登录按钮样式 */
.logout-container {
  margin-top: 20px;
  text-align: right;
}

.logout-btn {
  padding: 8px 15px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.logout-btn:hover {
  background-color: #e65c5c;
}
</style>